package com.common.server.modules.file.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.server.common.constant.Constant;
import com.common.server.common.exception.CustomerException;
import com.common.server.common.response.ResponseVo;
import com.common.server.common.util.FileUtil;
import com.common.server.common.util.IPUtils;
import com.common.server.common.util.StringUtils;
import com.common.server.common.util.Word2HtmlUtil;
import com.common.server.modules.file.entity.FileEntity;
import com.common.server.modules.file.mapper.FileMapper;
import com.common.server.modules.file.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author ostrich
 * @since 2019-10-08
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sys.config.uploadFilePath}")
    private String filePath;

    @Resource
    private FileMapper fileMapper;

    @Override
    public ResponseVo save(MultipartFile file, String path, FileEntity fileEntity) {
        //获取文件名
        String originalName = file.getOriginalFilename();

        String fileName = null;
        StringBuilder fileNameBuilder = new StringBuilder();
        if (StringUtils.isEmpty(fileEntity.getName())) {
            fileName = String.valueOf(fileNameBuilder.append(System.currentTimeMillis()));
        } else {
            fileName = fileEntity.getName();
        }

        //设置文件保存路径
        String fileUrl = filePath + path + File.separator;
        String fileType = originalName != null ? originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase() : "unKnown";
        try {
            //上传文件
            String fileCode = FileUtil.uploadFile(file, fileUrl, fileName + "." + fileType);
            BigDecimal bigDecimal = new BigDecimal(file.getSize());
            String size = bigDecimal.divide(new BigDecimal(1024))
                    .setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "KB";
            String ip = StringUtils.isNotEmpty(fileEntity.getIp()) ? fileEntity.getIp() : IPUtils.getLocalURI();
            fileEntity.setId(StringUtils.uuidGenerator()).setCode(fileCode).setIp(ip)
                    .setName(fileName + "." + fileType).setOldName(originalName).setUrl(fileUrl)
                    .setOrderIndex(String.valueOf(super.count()))
                    .setType(fileType).setAddDate(LocalDateTime.now()).setSize(size);
            //保存文件信息到文件表中
            fileMapper.insert(fileEntity);
            logger.info("上传【" + fileName + "】文件成功");
            return ResponseVo.ok(fileEntity);
        } catch (Exception e) {
            logger.error("上传【" + fileName + "】文件失败", e);
            return ResponseVo.error(Constant.Result.FAIL_CODE, Constant.Result.FAIL_MSG);
        }
    }

    @Override
    public String word2html(MultipartFile file, String url) {
        String originalFilename = file.getOriginalFilename();
        String res = null;
        //设置文件上传路径
        String tmpFilePath = filePath + "word2Html" + File.separator;
        //临时保存文件
        try {
            String fileName = FileUtil.saveFile(file.getInputStream(), originalFilename, tmpFilePath);
            if (fileName == null) {
                return JSON.toJSONString(ResponseVo.error("文件名不存在"));
            }

            //截取文件格式名
            String suffix = fileName.substring(fileName.indexOf(".") + 1);
            if ("docx".equals(suffix)) {
                res = Word2HtmlUtil.docxToHtml(tmpFilePath, fileName, url, fileMapper);
            } else {
                res = Word2HtmlUtil.docToHtml(tmpFilePath, fileName, url, fileMapper);
            }
            //删除临时文件
            FileUtil.deleteFile(tmpFilePath + fileName);
            return res;
        } catch (Exception e) {
            throw new CustomerException("word convert to html occur an exception ", e);
        }
    }
}
